import {
  getUserSchedule,
  addSchedule,
  editSchedule,
  deleteSchedule,
  querySchedule,
} from '../services/schedule';

export default {
  namespace: 'teachschedule',

  state: {
    teacherCourse: [],
    scheduleList: [],
  },

  effects: {
    *fetchUserSchedule(_, { call, put }) {
      const payload = { userno: localStorage.getItem('userno') };
      const response = yield call(getUserSchedule, payload);
      if (response.status) {
        yield put({
          type: 'saveTeacherCourse',
          payload: response.data,
        });
      }
    },
    *fetchScheduleList({ payload = {} }, { call, put }) {
      const response = yield call(querySchedule, payload);
      if (response.status) {
        yield put({
          type: 'saveScheduleList',
          payload: response.data,
        });
      }
    },
    *addSchedule({ payload }, { call, put }) {
      const data = yield call(addSchedule, payload);
      if (data.status) {
        const response = yield call(querySchedule, {});
        yield put({
          type: 'saveScheduleList',
          payload: response.data,
        });
      }
    },
    *removeSchedule({ payload }, { call, put }) {
      const data = yield call(deleteSchedule, payload);
      if (data.status) {
        const response = yield call(querySchedule, {});
        yield put({
          type: 'saveScheduleList',
          payload: response.data,
        });
      }
    },
    *updateSchedule({ payload }, { call, put }) {
      const data = yield call(editSchedule, payload);
      if (data.status) {
        const response = yield call(querySchedule, {});
        yield put({
          type: 'saveScheduleList',
          payload: response.data,
        });
      }
    },
  },

  reducers: {
    saveTeacherCourse(state, { payload }) {
      return {
        ...state,
        teacherCourse: payload,
      };
    },
    saveScheduleList(state, { payload }) {
      return {
        ...state,
        scheduleList: payload,
      };
    },
  },
};
